import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TankClient extends Frame {

    int x = 50;
    int y = 50;
    // 用于存储缓冲图片的成员
    Image offScreenImage = null;

    public void paint(Graphics g) {
        Color c = g.getColor();
        g.setColor(Color.red);
        g.fillOval(x, y, 30, 30);
        g.setColor(c);
        y += 5;
    }

    // 使用双缓冲解决实心圆移动闪烁问题，重写 update 方法，截获画出内容先进行存储，在一起画出
    public void update(Graphics g) {
        // 判断缓冲内容是否为空
        if (offScreenImage == null) {
            // 建立缓冲图片存入 offScreenImage 成员变量
            offScreenImage = this.createImage(800, 600);

        }
        // 拿到缓冲图片
        Graphics gOffScreen = offScreenImage.getGraphics();
        Color c = gOffScreen.getColor();
        // 将缓冲图片背景颜色设置绿色
        gOffScreen.setColor(Color.GREEN);
        // 画出窗口大小矩形（目的是每次清空缓冲图片内容）
        gOffScreen.fillRect(0, 0, 800, 600);
        // 恢复现场，画笔调回默认颜色
        gOffScreen.setColor(c);
        // 调用 paint 方法画入缓冲图片
        paint(gOffScreen);
        // 画出缓冲图片
        g.drawImage(offScreenImage, 0, 0, null);
    }

    public void lauchFrame() {
        this.setLocation(300, 100);
        this.setSize(800, 600);
        this.setTitle("TankWar");

        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        this.setResizable(false);
        this.setBackground(Color.GREEN);
        setVisible(true);
        new Thread(new PaintThreak()).start();
    }

    public static void main(String[] args) {
        TankClient tc = new TankClient();
        tc.lauchFrame();
    }

    private class PaintThreak implements Runnable {

        public void run() {
            while (true) {
                repaint();
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}